//
//  HXDEmoticonKeyboard.swift
//  weibo
//
//  Created by huxuedong on 15/12/15.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

private let HXDEmoticonCellID = "HXDEmoticonCell"

//1.遵守协议
class HXDEmoticonKeyboard: UIView, HXDEmoticonToolBarDelegate, UICollectionViewDataSource, UICollectionViewDelegate {
    
    private lazy var toolBar: HXDEmoticonToolBar = {
        let toolBar = HXDEmoticonToolBar(frame: CGRectZero)
        //2.成为代理
        toolBar.delegate = self
        return toolBar
    }()
    
    private lazy var emoticonCollectionView: UICollectionView = {
        //初始化layout
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        //设置滚动方向
        layout.scrollDirection = .Horizontal
        //通过layout初始化collectionView
        let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.clearColor()
        collectionView.registerClass(HXDEmoticonCell.self, forCellWithReuseIdentifier: HXDEmoticonCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.pagingEnabled = true
        collectionView.bounces = false
        return collectionView
    }()
    
    private lazy var emoticonPageControl: UIPageControl = {
        let pageControl = UIPageControl()
        //_currentPageImage和_pageImage为UIPageControl的隐藏属性，需利用KVC为其赋值
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        return pageControl
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(emoticonPageControl)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(self)
            make.height.equalTo(37)
        }
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.width.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
            make.leading.equalTo(self)
        }
        emoticonPageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        //主线程异步执行
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.chooseButtonWithType(.Default)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //根据emoticonCollectionView的宽高设置布局的宽高
        layout.itemSize = emoticonCollectionView.size
    }

}

extension HXDEmoticonKeyboard {
    
    //3.实现代理方法，根据点击的toolBar切换到对应的表情图片页
    func chooseButtonWithType(type: HXDEmoticonType) {
        let indexPath: NSIndexPath
        switch type{
        case .Recent:
            indexPath = NSIndexPath(forItem: 0, inSection: 0)
        case .Default:
            indexPath = NSIndexPath(forItem: 0, inSection: 1)
        case .Emoji:
            indexPath = NSIndexPath(forItem: 0, inSection: 2)
        case .Lxh:
            indexPath = NSIndexPath(forItem: 0, inSection: 3)
        }
        //切换emoticonCollectionView到对应的indexPath(每组的第0页)
        emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        //更新pageControll
        updatePageController(indexPath)
    }
    
    private func updatePageController(indexPath: NSIndexPath) {
        //设置总页数
        emoticonPageControl.numberOfPages = HXDEmoticonTools.sharedInstance.allEmoticons[indexPath.section].count
        //设置当前页(每组中第几页)
        emoticonPageControl.currentPage = indexPath.item
        //第0组时(最近使用的表情)，隐藏emoticonPageControl
        emoticonPageControl.hidden = indexPath.section == 0
    }
    
    //数据源方法
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return HXDEmoticonTools.sharedInstance.allEmoticons.count
    }
    
    //数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HXDEmoticonTools.sharedInstance.allEmoticons[section].count
    }
    
    //数据源方法
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HXDEmoticonCellID, forIndexPath: indexPath) as! HXDEmoticonCell
        cell.emoticons = HXDEmoticonTools.sharedInstance.allEmoticons[indexPath.section][indexPath.item]
        cell.indexPath = indexPath
        return cell
    }
    
    //代理方法，根据表情图片页选中对应的toolBar
    func scrollViewDidScroll(scrollView: UIScrollView) {
        //当前界面上显示的cell的数组
        let cells = emoticonCollectionView.visibleCells()
        if cells.count == 2 {
            let firstCell = cells.first!
            let secondCell = cells.last!
            //计算绝对值：firstCell.x和secondCell.x的值不会改变，当collectionView中的cell布局好之后，每个cell的x,y,w,h就确定不变了。contentOffset.x会随着collectionView的滚动而改变，往左往上滑动为正值，往右往下滑动为负值。
            let firstCellVisibleW = abs(Int32(firstCell.x - scrollView.contentOffset.x))
            let secondCellVisibleW = abs(Int32(secondCell.x - scrollView.contentOffset.x))
            let cell: UICollectionViewCell
            //绝对值小的显示的多
            if firstCellVisibleW < secondCellVisibleW {
                cell = firstCell
            } else {
                cell = secondCell
            }
            //获取到cell的indexPath
            let indexPath = emoticonCollectionView.indexPathForCell(cell)!
            //设置选中的toolBar为当前cell所在的组数
            toolBar.currentSection = indexPath.section
            //更新pageControll
            updatePageController(indexPath)
        }
    }
    
}
